import React from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Modal,
  Upload,
  Space,
  Tabs,
  Select,
  Radio,
  InputNumber,
  TreeSelect,
} from 'antd';
import { ExclamationCircleOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import moment from 'moment';
import Categories from '../../admin/categories';

const currControl = 'Edu_QuestionBank';
const { confirm } = Modal;
const { TabPane } = Tabs;

class QuestionBankEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      imageUrl: '',
      imgList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData } = this.props;
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
    }
    this.fetchCategory();
  }
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;
        if (result.image) {
          this.setState({ imageUrl: result.image });
        }
        if (result.startTime) result.startTime = moment(result.startTime);
        if (result.endTime) result.endTime = moment(result.endTime);
        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  onFinish = async (values: any) => {
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    if (this.state.imageUrl) {
      values.model.image = this.state.imageUrl;
    }
    const { cascaderOption } = this.state;
    var cate = cascaderOption.filter((o: any) => o.value == values.model.bType)[0];
    if (cate) values.model.bType = cate.node.categoryName;
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.props.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  onChange = (value: number[]) => {
    this.setState({
      inputValue: value,
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'done' && info.file.response) {
      this.setState({
        imageUrl: info.file.response.result,
      });
    }
  };
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'question' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  render() {
    const { datas, loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="题库编辑" key="1">
              <Form.Item label="id" name={['model', 'id']} hidden>
                <Input />
              </Form.Item>
              <Form.Item name={['model', 'bankNum']} label="题库编号" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item name={['model', 'orderId']} label="排序号" rules={[{ required: true }]}>
                <InputNumber />
              </Form.Item>
              <Form.Item name={['model', 'title']} label="题库标题" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item name={['model', 'sex']} label="适合儿童性别">
                <Radio.Group>
                  <Radio value="1">男</Radio>
                  <Radio value="0">女</Radio>
                  <Radio value="">不限</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }} label="题库分类">
                <Input.Group compact>
                  <Form.Item name={['model', 'bType']} rules={[{ required: true }]}>
                    <TreeSelect
                      value={this.state.value}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={this.state.cascaderOption}
                      placeholder="请选择"
                      treeDefaultExpandAll
                      style={{ width: 240 }}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button
                      icon={<PlusOutlined />}
                      onClick={() => this.openModal(null, 'question')}
                    >
                      题库分类
                    </Button>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'adapt']} label="儿童类型">
                    <Select style={{ width: 200 }}>
                      <Select.Option value="1">足月儿</Select.Option>
                      <Select.Option value="0">早产儿</Select.Option>
                    </Select>
                  </Form.Item>
                  <Form.Item name={['model', 'age']} label="适龄范围" rules={[{ required: true }]}>
                    <InputNumber min={0} />
                  </Form.Item>
                  <Form.Item name={['model', 'ageMax']} label="（月）" rules={[{ required: true }]}>
                    <InputNumber min={0} />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item name={['model', 'memo']} label="备注">
                <Input.TextArea rows={6} />
              </Form.Item>
            </TabPane>
            <TabPane tab="图片" key="2">
              <Form.Item>
                <Upload
                  action={UploadUtil.actionURL}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: currControl,
                    objectField: 'image',
                  }}
                  name="files"
                  listType="picture-card"
                  showUploadList={false}
                  beforeUpload={UploadUtil.beforeUpload}
                  onChange={this.handleUpload}
                >
                  {imageUrl ? (
                    <img
                      src={UploadUtil.imgServ + imageUrl}
                      alt="avatar"
                      style={{ width: '100%', height: '100%' }}
                    />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </Form.Item>
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Modal
          title="题库分类"
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible: false })}
          width={700}
          footer={false}
        >
          <Categories layout={this.state.layout} size="small" fetchCategory={this.fetchCategory} />
        </Modal>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(QuestionBankEdit);
